package com.tca.common.web.handler;

import com.tca.common.web.bean.LogRecordBean;
import com.tca.common.web.config.LogRecordListenerExecutorConfig;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhoua
 * @date 2022/1/12 21:31
 */
public abstract class AbstractLogRecordListener implements LogRecordListener {

    private AtomicInteger num = new AtomicInteger();

    /**
     * 日志处理器执行器配置
     */
    private LogRecordListenerExecutorConfig logRecordListenerExecutorConfig;

    /**
     * 日志处理器执行器
     */
    private ExecutorService executor;

    public AbstractLogRecordListener(LogRecordListenerExecutorConfig logRecordListenerExecutorConfig) {
        init(logRecordListenerExecutorConfig);
    }

    private void init(LogRecordListenerExecutorConfig logRecordListenerExecutorConfig) {
        this.logRecordListenerExecutorConfig = logRecordListenerExecutorConfig;
        executor = new ThreadPoolExecutor(logRecordListenerExecutorConfig.getCore(), logRecordListenerExecutorConfig.getMax(),
                logRecordListenerExecutorConfig.getKeepAliveTime(), TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
                r -> new Thread(r, "log-" + num.incrementAndGet() + "-thread-pool"));
    }

    @Override
    public final void onLogRecordEvent(LogRecordBean logRecordBean) {
        executor.submit(() -> doHandle(logRecordBean));
    }


}
